<script setup lang="ts">
import { reqCouponList, reqDeleteCoupon, reqAddCoupon, reqUpdateCoupon, reqUpdateCouponStatus } from '@/api/coupon'
import { useInitTable, useInitForm } from '@/composables/useCommon'
const {
  tableData,
  loading,
  getData,
  handleDelete,
  handleStatusChange,
  currentPage,
  pageSize,
  total,
  tableRef,
  handleDeleteAll,
  handleSelectionChange
} = useInitTable({
  getList: reqCouponList,
  delete: reqDeleteCoupon,
  updateStatus: reqUpdateCouponStatus,
  onGetListSuccess: (res: any) => {
    tableData.value = res.data.list.map((item: any) => {
      item.statusText = formatStatus(item)
      return item
    })
  }
})

const { formDrawerRef, formRef, drawerTitle, form, rules, handleSubmit, handleAdd, handleEdit } = useInitForm({
  getData,
  initialForm: {
    name: '',
    type: 0,
    value: 0,
    total: 100,
    min_price: 0,
    start_time: null,
    end_time: '',
    order: 50,
    desc: ''
  },
  rules: {
    name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }]
  },
  update: reqUpdateCoupon,
  create: reqAddCoupon,
  onBeforeSubmit: (f: any) => {
    // 日期时间转为时间戳
    if (typeof f.start_time !== 'number') {
      f.start_time = new Date(f.start_time).getTime()
    }
    if (typeof f.end_time !== 'number') {
      f.end_time = new Date(f.end_time).getTime()
    }
    return f
  }
})

// 生成时间范围
const timerange = computed({
  get() {
    return form.start_time && form.end_time ? [form.start_time, form.end_time] : []
  },
  set(val) {
    form.start_time = val[0]
    form.end_time = val[1]
  }
})

// 判断优惠券状态
function formatStatus(row: any) {
  let status = '领取中'
  let now = new Date().getTime()
  let start = new Date(row.start_time).getTime()
  let end = new Date(row.end_time).getTime()
  if (start > now) {
    status = '未开始'
  } else if (end < now) {
    status = '已过期'
  }
  if (row.status == 0) {
    status = '已失效'
  }
  return status
}
</script>

<template>
  <div>
    <el-card shadow="never" style="border: 0; margin: 10px">
      <ListHeader @refresh="getData" @create="handleAdd" />
      <el-table ref="tableRef" v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column label="优惠券名称" width="360">
          <template #default="{ row }">
            <div class="title" :class="row.statusText == '领取中' ? 'active' : 'inactive'">
              <h5 style="font-size: 16px; font-weight: bold; margin-bottom: 8px">
                {{ row.name }}
              </h5>
              <small>{{ row.start_time }} ~{{ row.end_time }}</small>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="statusText" label="状态" />
        <el-table-column label="优惠">
          <template #default="{ row }">
            {{ row.type == 0 ? '满减 ' : '折扣 ' }}{{ row.type == 0 ? '¥' + row.value : row.value + ' 折' }}
          </template>
        </el-table-column>
        <el-table-column prop="total" label="发行数量" />
        <el-table-column prop="used" label="已使用" />
        <el-table-column prop="value" label="面值" />
        <el-table-column prop="min_price" label="最低使用价格" />
        <el-table-column prop="order" label="排序" width="100" />

        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button
              v-if="scope.row.statusText == '未开始'"
              type="primary"
              text
              size="small"
              icon="edit"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              v-if="scope.row.statusText != '领取中'"
              title="是否确认要删除吗?"
              width
              @confirm="handleDelete(scope.row.id)"
            >
              <template #reference>
                <el-button size="small" text type="info" icon="delete">删除</el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm
              v-if="scope.row.statusText == '领取中'"
              title="是否确认要让该优惠券失效?"
              width
              confirmButtonText="失效"
              @confirm="handleStatusChange(scope.row, 0)"
            >
              <template #reference>
                <el-button size="small" type="danger">失效</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next, total"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="getData"
        ></el-pagination>
      </div>
    </el-card>

    <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit" destroyOnClose>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名称" style="width: 50%" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :value="0" border>满减</el-radio>
            <el-radio :value="1" border>折扣</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="面值" prop="value">
          <el-input v-model="form.value" style="width: 30%">
            <template #append>
              {{ form.type ? '折' : '元' }}
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="发行量" prop="total">
          <el-input-number v-model="form.total" :min="1" :max="10000" style="width: 30%" />
        </el-form-item>
        <el-form-item label="最低使用价格" prop="min_price">
          <el-input type="number" :min="0" v-model="form.min_price" style="width: 30%" />
        </el-form-item>
        <el-form-item label="活动时间">
          <el-date-picker
            :editable="false"
            v-model="timerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" :row="5" v-model="form.desc" placeholder="请输入优惠券说明" />
        </el-form-item>
        <el-form-item label="排序" prop="order">
          <el-input-number v-model="form.order" :min="0" :max="999" style="width: 30%" />
        </el-form-item>
      </el-form>
    </FormDrawer>
  </div>
</template>

<style lang="scss" scoped>
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}
.title {
  border: 1px dashed #ccc;
  padding: 10px 20px;
  border-radius: 5px;
}
.active {
  border-color: #ffd4d8;
  background-color: #fff5f8;
  color: #fc8070;
}
.inactive {
  border-color: #e9e8eb;
  background-color: #fbfbfb;
  color: #a3a2ab;
}
</style>
